from rest_framework import serializers
from .models import Project
from logs.models import ErrorLog
from django.utils import timezone
from datetime import timedelta

class ProjectSerializer(serializers.ModelSerializer):
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    error_count = serializers.SerializerMethodField()
    api_key = serializers.CharField(read_only=True)
    
    class Meta:
        model = Project
        fields = [
            'id', 'name', 'description', 'status', 'api_key', 
            'owner', 'owner_name', 'error_count', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'api_key', 'owner', 'created_at', 'updated_at']
    
    def get_error_count(self, obj):
        """获取项目的错误日志数量"""
        return ErrorLog.objects.filter(project=obj).count()
    
    def create(self, validated_data):
        """创建项目时自动设置所有者"""
        validated_data['owner'] = self.context['request'].user
        return super().create(validated_data)
    
    def validate_name(self, value):
        """验证项目名称唯一性"""
        user = self.context['request'].user
        if Project.objects.filter(owner=user, name=value).exists():
            raise serializers.ValidationError('您已经有一个同名的项目了')
        return value

class ProjectDetailSerializer(ProjectSerializer):
    """项目详情序列化器，包含更多信息"""
    recent_errors = serializers.SerializerMethodField()
    total_logs = serializers.SerializerMethodField()
    recent_error_trend = serializers.SerializerMethodField()
    
    class Meta(ProjectSerializer.Meta):
        fields = ProjectSerializer.Meta.fields + ['recent_errors', 'total_logs', 'recent_error_trend']
    
    def get_recent_errors(self, obj):
        """获取最近的错误日志"""
        recent_errors = ErrorLog.objects.filter(project=obj).order_by('-timestamp')[:5]
        return [{
            'id': error.id,
            'level': error.level,
            'message': error.message[:100],
            'timestamp': error.timestamp.strftime('%Y-%m-%d %H:%M:%S')
        } for error in recent_errors]
    
    def get_total_logs(self, obj):
        """获取总日志数量"""
        return ErrorLog.objects.filter(project=obj).count()
    
    def get_recent_error_trend(self, obj):
        """获取最近7天的错误趋势"""
        end_date = timezone.now()
        start_date = end_date - timedelta(days=7)
        
        daily_errors = []
        for i in range(7):
            day = start_date + timedelta(days=i)
            day_start = day.replace(hour=0, minute=0, second=0, microsecond=0)
            day_end = day_start + timedelta(days=1)
            
            count = ErrorLog.objects.filter(
                project=obj,
                timestamp__gte=day_start,
                timestamp__lt=day_end
            ).count()
            
            daily_errors.append({
                'date': day.strftime('%Y-%m-%d'),
                'count': count
            })
        
        return daily_errors

class ProjectCreateSerializer(serializers.ModelSerializer):
    """项目创建专用序列化器"""
    
    class Meta:
        model = Project
        fields = ['name', 'description']
    
    def validate_name(self, value):
        """验证项目名称"""
        if len(value.strip()) < 2:
            raise serializers.ValidationError('项目名称至少需要2个字符')
        
        user = self.context['request'].user
        if Project.objects.filter(owner=user, name=value).exists():
            raise serializers.ValidationError('您已经有一个同名的项目了')
        
        return value.strip()
    
    def validate_description(self, value):
        """验证项目描述"""
        if value and len(value.strip()) > 500:
            raise serializers.ValidationError('项目描述不能超过500个字符')
        return value.strip() if value else ''